package com.fancon.android.push;

import com.fancon.rage.comic.vn.R;
import com.fancon.rage.comic.vn.activity.RageVietActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;

public class C2DMMessageReceiver extends BroadcastReceiver {

	String payload;
	static int id = 0;
	String contentTitle = "message";
	String contentText = "New message received C2DM app";
	Notification notification;
	NotificationManager notificationManager;

	@Override
	public void onReceive(Context context, Intent intent) {
		notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		String action = intent.getAction();
		Log.w("C2DM", "Message Receiver called");
		if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
			Log.w("C2DM", "Received message");
			payload = intent.getStringExtra("payload");
			Log.d("C2DM", "dmControl: payload = " + payload);
			if (id >= 2) {
				contentTitle = "hihi";
				contentText = "hehe";

			}
			// TODO Send this to my application server to get the real data
			// Lets make something visible to show that we received the message
			createNotification(context, payload);
			Log.d("id_notify", "" + id);
			sendMessage(context, payload);
		}
	}

	private void sendMessage(Context context, String payload) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		Editor edit = prefs.edit();
		edit.putString("payload", payload);
		edit.commit();
	}

	public void createNotification(Context context, String payload) {
		notification = new Notification(R.drawable.iconmessage,
				"New message from application server",
				System.currentTimeMillis());
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		id++;
		notification.number = id;
		// notification.iconLevel = 1;
		// Intent intent = new Intent(context, MessageReceivedActivity.class);
		// intent.putExtra("payload", payload);
		Intent intent = new Intent(context, RageVietActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				intent, 0);
		notification.setLatestEventInfo(context, contentTitle, contentText,
				pendingIntent);
		notificationManager.notify(0, notification);

	}
}